// src/stores/video/background.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getBackgrounds, getBackground, deleteBackground, uploadBackground } from '@/api/video/background.js'

export const useBackgroundStore = defineStore('background', () => {
    // 状态
    const backgrounds = ref([])
    const currentBackground = ref(null)
    const loading = ref(false)
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(12)
    const fileType = ref('')
    const keyword = ref('')

    // 计算属性
    const imageBackgrounds = computed(() =>
        backgrounds.value.filter(bg => bg.fileType === 'image')
    )

    const videoBackgrounds = computed(() =>
        backgrounds.value.filter(bg => bg.fileType === 'video')
    )

    // 获取背景资源列表
    async function fetchBackgrounds(params = {}) {
        loading.value = true
        try {
            const queryParams = {
                page: params.page || currentPage.value,
                pageSize: params.pageSize || pageSize.value,
                type: params.type !== undefined ? params.type : fileType.value,
                keyword: params.keyword !== undefined ? params.keyword : keyword.value
            }

            const res = await getBackgrounds(queryParams)
            if (res.code === 200 && res.data) {
                backgrounds.value = res.data.records || []
                total.value = res.data.total || 0

                // 更新分页信息
                if (params.page) currentPage.value = params.page
                if (params.pageSize) pageSize.value = params.pageSize
                if (params.type !== undefined) fileType.value = params.type
                if (params.keyword !== undefined) keyword.value = params.keyword
            }
            return res
        } catch (error) {
            console.error('获取背景资源失败:', error)
            return { code: 500, message: '获取背景资源失败' }
        } finally {
            loading.value = false
        }
    }

    // 获取背景资源详情
    async function fetchById(id) {
        loading.value = true
        try {
            const res = await getBackground(id)
            if (res.code === 200 && res.data) {
                currentBackground.value = res.data
            }
            return res
        } catch (error) {
            console.error('获取背景资源详情失败:', error)
            return { code: 500, message: '获取背景资源详情失败' }
        } finally {
            loading.value = false
        }
    }

    // 删除背景资源
    async function removeBackground(id) {
        try {
            const res = await deleteBackground(id)
            if (res.code === 200) {
                // 从列表中移除
                const index = backgrounds.value.findIndex(bg => bg.id === id)
                if (index !== -1) {
                    backgrounds.value.splice(index, 1)
                }
            }
            return res
        } catch (error) {
            console.error('删除背景资源失败:', error)
            return { code: 500, message: '删除背景资源失败' }
        }
    }

    // 批量删除背景资源
    async function batchRemoveBackgrounds(ids) {
        try {
            const results = await Promise.all(ids.map(id => deleteBackground(id)))

            // 统计成功和失败的数量
            const successCount = results.filter(res => res.code === 200).length

            // 刷新列表
            if (successCount > 0) {
                await fetchBackgrounds()
            }

            return {
                code: 200,
                data: {
                    total: ids.length,
                    success: successCount,
                    failed: ids.length - successCount
                }
            }
        } catch (error) {
            console.error('批量删除背景资源失败:', error)
            return { code: 500, message: '批量删除背景资源失败' }
        }
    }

    // 上传背景资源
    async function upload(file, fileType) {
        try {
            const formData = new FormData()
            formData.append('file', file)
            formData.append('fileType', fileType)

            const res = await uploadBackground(formData)
            if (res.code === 200 && res.data) {
                // 刷新列表
                await fetchBackgrounds()
            }
            return res
        } catch (error) {
            console.error('上传背景资源失败:', error)
            return { code: 500, message: '上传背景资源失败' }
        }
    }

    return {
        // 状态
        backgrounds,
        currentBackground,
        loading,
        total,
        currentPage,
        pageSize,
        fileType,
        keyword,

        // 计算属性
        imageBackgrounds,
        videoBackgrounds,

        // 操作方法
        getBackgrounds: fetchBackgrounds,
        fetchById,
        removeBackground,
        batchRemoveBackgrounds,
        upload
    }
})